<!--使用SockJS配置了浏览器不支持WebSocket技术时的替代方案-->
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta content="text/html;charset=UTF-8"/>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>WebSocket Examples: Reverse</title>
    <script src="/webjars/jquery/3.1.1-1/jquery.min.js"></script>
    <script src="/webjars/sockjs-client/1.0.2/sockjs.min.js"></script>
    <script src="/webjars/stomp-websocket/2.3.3/stomp.min.js"></script>
    <script th:src="@{/layui/layui.js}"></script>
    <link th:href="@{/layui/css/layui.css}" rel="stylesheet">
    <style type="text/css">
        #connect-container {
            margin: 0 auto;
            width: 400px;
        }

        #connect-container div {
            padding: 5px;
            margin: 0 7px 10px 0;
        }

        .layui-btn {
            display: inline-block;
        }
    </style>
</head>
<body>
<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websockets rely on Javascript being
    enabled. Please enable
    Javascript and reload this page!</h2></noscript>
<div>
    <div id="connect-container" class="layui-elem-field">
        <legend>chat With SockJS！</legend>
        <div>
            <input id="url" type="text" class="layui-input" size="40" style="width: 400px" value="/broker"/>
        </div>
        <div>
            <span>用户名：</span>
            <input id="name" type="text" class="layui-input" size="10" value="pwd"/>
        </div>
        <div>
            <button id="connect" class="layui-btn layui-btn-normal" onclick="connect();">Connect</button>
            <button id="disconnect" class="layui-btn layui-btn-normal layui-btn-disabled" disabled="disabled"
                    onclick="disconnect();">Disconnect
            </button>
        </div>
        <div>
            <textarea id="message" class="layui-textarea" placeholder="请输入请求的内容" style="width: 350px; margin-right: 10px"></textarea><br/>
            <span>发送给：</span>
            <input id="target" type="text" class="layui-input" size="10" placeholder="发送给谁"/>
            <button id="echo" class="layui-btn layui-btn-normal layui-btn-disabled" disabled="disabled" onclick="echo();">Send</button>
        </div>
        <hr/>
        <div id="content"></div>
    </div>
</div>
</body>
</html>

<script type="text/javascript">
    var stompClient = null;

    $(function () {
        var url = $("#url");
        if (window.location.protocol === 'http:') {
            url.val('http://' + window.location.host + url.val());
        } else {
            url.val('https://' + window.location.host + url.val());
        }
    });

    function setConnected(connected) {
        var connect = $("#connect");
        var disconnect = $("#disconnect");
        var echo = $("#echo");

        if (connected) {
            connect.addClass("layui-btn-disabled");
            disconnect.removeClass("layui-btn-disabled");
            echo.removeClass("layui-btn-disabled");
        } else {
            connect.removeClass("layui-btn-disabled");
            disconnect.addClass("layui-btn-disabled");
            echo.addClass("layui-btn-disabled");
        }

        connect.attr("disabled", connected);
        disconnect.attr("disabled", !connected);
        echo.attr("disabled", !connected);
    }

    //连接
    function connect() {
        var url = $("#url").val();
        var user = $("#name").val();

        // 建立连接对象（还未发起连接）
        var socket = new SockJS(url);
        // 获取 STOMP 子协议的客户端对象
        stompClient = Stomp.over(socket);
        stompClient.connect(
            {name: user},//客户端认证信息
            function (frame) {
                setConnected(true);
                log('Info: WebSocket connection opened.' + frame);
                stompClient.subscribe('/topic/message', function (message) {
                    print('[/topic/message] Received: ' + message.body);
                });
                stompClient.subscribe('topic/' + user, function (message) {
                    print('[topic/' + user + '] Received: ' + message.body);
                });
                stompClient.subscribe('user/resp', function (message) {
                    print('[user/resp] Received: ' + message.body);
                });
            },
            function (error) {
                setConnected(false);
                log('Info: WebSocket connection error：' + error);
            }
        );
    }

    //断开连接
    function disconnect() {
        if (stompClient != null) {
            stompClient.disconnect();
            stompClient = null;
        }
        setConnected(false);
    }

    //Echo
    function echo() {
        if (stompClient != null) {
            var message = $("#message").val();
            var target = $("#target").val();
            var headers = {user: $("#name").val()};
            var destination = '/app/resp';//发送给自己
            if (target == 'all') {//广播
                destination = '/app/broadcast';
                headers.target = target;
            } else if (target != null && target != '') {//发送给指定的人
                destination = '/app/chat';
                headers.target = target;
            }
            stompClient.send(destination, headers, message);
        } else {
            alert('WebSocket connection not established, please connect.');
        }
    }

    //日志输出
    function log (message) {
        console.debug(message);
    }

    function print (message) {
        $("#content").append("<p>" + message + "</p>");
    }
</script>